package com.north.light.libullet;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * FileName: BulletRecyclerView
 * Author: lzt
 * Date: 2022/9/15 13:59
 * 弹幕recyclerview
 */
public class BulletRecyclerView extends RecyclerView {

    /**
     * 弹幕BulletInfoAdapter
     */
    private BulletInfoAdapter mInfoAdapter;
    /**
     * 设置数据缓存
     */
    private List<BulletInfo> mBulletCacheList = new ArrayList<>();

    private Timer mTimer;

    /**
     * handler
     */
    private Handler handler = new Handler(Looper.getMainLooper());


    private long mSetDataInterval = 0;

    public BulletRecyclerView(@NonNull Context context) {
        super(context);
        initViewData();
    }

    public BulletRecyclerView(@NonNull Context context, AttributeSet attrs) {
        super(context, attrs);
        initViewData();
    }

    public BulletRecyclerView(@NonNull Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViewData();
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return false;
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        clearHandler();
        super.onDetachedFromWindow();
    }

    private void clearHandler() {
        try {
            if (handler != null) {
                handler.removeCallbacksAndMessages(null);
            }
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
        } catch (Exception e) {

        }
    }

    private void startHandler() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    smoothScrollBy(0, 6);
                    //检查是否滑动到了底部
                    checkScrollToBottom();
                } catch (Exception e) {

                }
            }
        }, 10, 80);
    }

    private void initViewData() {
        setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        setOverScrollMode(OVER_SCROLL_NEVER);
        mInfoAdapter = new BulletInfoAdapter();
        setAdapter(mInfoAdapter);
    }

    public void clearData() {
        if (mInfoAdapter != null) {
            mInfoAdapter.clear();
        }
    }


    private void checkScrollToBottom() {
        //监听回调--------------------------------------------------
        try {
            //int offset, int progress, int duration, float percent
            //verticalOffset, verticalOffset + verticalExtent, verticalTotal,
            // (((verticalOffset + verticalExtent) * 1.0f) / (verticalTotal * 1.0f))
            int verticalExtent = computeVerticalScrollExtent();
            int verticalOffset = computeVerticalScrollOffset();
            int verticalTotal = computeVerticalScrollRange();
            float percent = (((verticalOffset + verticalExtent) * 1.0f) / (verticalTotal * 1.0f));
            if (percent == 1) {
                //已经到底了
                if (mInfoAdapter != null && mInfoAdapter.getData() != null &&
                        mInfoAdapter.getData().size() != 0) {
                    //重新设置数据
                    List<BulletInfo> trainResult = new ArrayList<>();
                    for (BulletInfo bulletInfo : mBulletCacheList) {
                        BulletInfo cache = new BulletInfo();
                        cache.setType(bulletInfo.getType());
                        cache.setContent(bulletInfo.getContent());
                        cache.setNickName(bulletInfo.getNickName());
                        trainResult.add(cache);
                    }
                    setData(trainResult);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //外部调用方法-----------------------------------------------------------------------------------

    /**
     * 设置数据
     */
    public void setData(List<BulletInfo> bulletList) {
        if (handler == null) {
            return;
        }
        if (System.currentTimeMillis() - mSetDataInterval < 1000) {
            return;
        }
        mSetDataInterval = System.currentTimeMillis();
        clearHandler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                //克隆数据
                List<BulletInfo> trainList = new ArrayList<>();
                if (bulletList == null || bulletList.size() == 0) {
                    trainList = new ArrayList<>();
                } else {
                    for (BulletInfo bulletInfo : bulletList) {
                        BulletInfo cache = new BulletInfo();
                        cache.setType(bulletInfo.getType());
                        cache.setContent(bulletInfo.getContent());
                        cache.setNickName(bulletInfo.getNickName());
                        trainList.add(cache);
                    }
                }
                mBulletCacheList.clear();
                mBulletCacheList.addAll(trainList);
                if (mInfoAdapter != null) {
                    mInfoAdapter.clear();
                    mInfoAdapter.setData(trainList);
                }
                scrollToPosition(0);
                startHandler();
            }
        });
    }


}
